import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'
import type {
  AuthResponse,
  LoginRequest,
  RegisterRequest,
  User,
  ChatRoom,
  Message,
  SendMessageRequest,
  CreateChatRoomRequest,
  ChatHistory,
  ChangePasswordRequest,
  CreateDirectChatRequest,
  EditMessageRequest,
  UploadResult
} from '@/types'

class ApiService {
  private api: AxiosInstance

  constructor() {
    this.api = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL || 'https://localhost:7000/api',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    })

    // 请求拦截器 - 添加认证token
    this.api.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('auth_token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器 - 处理错误
    this.api.interceptors.response.use(
      (response: AxiosResponse) => {
        return response
      },
      (error) => {
        if (error.response?.status === 401) {
          // Token过期或无效，清除本地存储并跳转到登录页
          localStorage.removeItem('auth_token')
          localStorage.removeItem('user_info')
          window.location.href = '/login'
        }
        return Promise.reject(error)
      }
    )
  }

  // 认证相关
  async login(data: LoginRequest): Promise<AuthResponse> {
    const response = await this.api.post<AuthResponse>('/auth/login', data)
    return response.data
  }

  async register(data: RegisterRequest): Promise<AuthResponse> {
    const response = await this.api.post<AuthResponse>('/auth/register', data)
    return response.data
  }

  async logout(): Promise<void> {
    await this.api.post('/auth/logout')
  }

  async getCurrentUser(): Promise<User> {
    const response = await this.api.get<User>('/auth/me')
    return response.data
  }

  async updateCurrentUser(data: Partial<User>): Promise<User> {
    const response = await this.api.put<User>('/auth/me', data)
    return response.data
  }

  async changePassword(data: ChangePasswordRequest): Promise<void> {
    await this.api.post('/auth/change-password', data)
  }

  async searchUsers(searchTerm: string): Promise<User[]> {
    const response = await this.api.get<User[]>(`/auth/search?searchTerm=${encodeURIComponent(searchTerm)}`)
    return response.data
  }

  // 聊天室相关
  async createChatRoom(data: CreateChatRoomRequest): Promise<ChatRoom> {
    const response = await this.api.post<ChatRoom>('/chat/rooms', data)
    return response.data
  }

  async getUserChatRooms(): Promise<ChatRoom[]> {
    const response = await this.api.get<ChatRoom[]>('/chat/rooms')
    return response.data
  }

  async getChatRoom(chatRoomId: number): Promise<ChatRoom> {
    const response = await this.api.get<ChatRoom>(`/chat/rooms/${chatRoomId}`)
    return response.data
  }

  async createDirectChat(data: CreateDirectChatRequest): Promise<ChatRoom> {
    const response = await this.api.post<ChatRoom>('/chat/rooms/direct', data)
    return response.data
  }

  async joinChatRoom(chatRoomId: number): Promise<void> {
    await this.api.post(`/chat/rooms/${chatRoomId}/join`)
  }

  async leaveChatRoom(chatRoomId: number): Promise<void> {
    await this.api.post(`/chat/rooms/${chatRoomId}/leave`)
  }

  async markAsRead(chatRoomId: number): Promise<void> {
    await this.api.post(`/chat/rooms/${chatRoomId}/mark-read`)
  }

  async getChatRoomMembers(chatRoomId: number): Promise<User[]> {
    const response = await this.api.get<User[]>(`/chat/rooms/${chatRoomId}/members`)
    return response.data
  }

  // 消息相关
  async sendMessage(data: SendMessageRequest): Promise<Message> {
    const response = await this.api.post<Message>('/chat/messages', data)
    return response.data
  }

  async getChatHistory(
    chatRoomId: number, 
    pageNumber: number = 1, 
    pageSize: number = 50
  ): Promise<ChatHistory> {
    const response = await this.api.get<ChatHistory>(
      `/chat/rooms/${chatRoomId}/messages?pageNumber=${pageNumber}&pageSize=${pageSize}`
    )
    return response.data
  }

  async deleteMessage(messageId: number): Promise<void> {
    await this.api.delete(`/chat/messages/${messageId}`)
  }

  async editMessage(messageId: number, data: EditMessageRequest): Promise<Message> {
    const response = await this.api.put<Message>(`/chat/messages/${messageId}`, data)
    return response.data
  }

  // 文件上传相关
  async uploadAvatar(file: File): Promise<UploadResult> {
    const formData = new FormData()
    formData.append('file', file)

    const response = await this.api.post<UploadResult>('/file/upload-avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }
}

export const apiService = new ApiService()
export default apiService
